#include "nvs_driver.h"

static const char *TAG = "nvs_driver";
void nvs_init(void)
{
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_LOGE(TAG, "Error init NVS : %s",esp_err_to_name(ret));
        ESP_ERROR_CHECK(nvs_flash_erase());
        ESP_ERROR_CHECK(nvs_flash_init());
    }
}

void nvs_deinit(void)
{
    nvs_flash_deinit();
}

int32_t nvs_read(const char *namespace_name, const char *key)
{
    nvs_handle_t my_handle;
    esp_err_t err = nvs_open(namespace_name, NVS_READWRITE, &my_handle);
    if (err != ESP_OK)
    {
        ESP_LOGE(TAG, "Error (%s) opening NVS handle!", esp_err_to_name(err));
    }
    else
    {
        ESP_LOGI(TAG, "Reading value from NVS ... ");
        int32_t value = 0;
        err = nvs_get_i32(my_handle, key, &value);
        switch (err)
        {
        case ESP_OK:
            ESP_LOGI(TAG, "Done");
            ESP_LOGI(TAG, "key:%s,val:%d", key, value);
            break;
        case ESP_ERR_NVS_NOT_FOUND:
            ESP_LOGI(TAG, "The value is not initialized yet!");
            break;
        default:
            ESP_LOGI(TAG, "Error (%s) reading!", esp_err_to_name(err));
        }
        nvs_close(my_handle);
        return value;
    }
    return 0;
}

void nvs_write(const char *namespace_name, const char *key, int32_t value)
{
    nvs_handle_t my_handle;
    esp_err_t err = nvs_open(namespace_name, NVS_READWRITE, &my_handle);
    if (err != ESP_OK)
    {
        ESP_LOGE(TAG, "Error (%s) opening NVS handle!", esp_err_to_name(err));
    }
    else
    {
        ESP_LOGI(TAG, "writing value into NVS ... ");
        err = nvs_set_i32(my_handle, key, value);
        printf((err != ESP_OK) ? "Failed!\n" : "Done\n");

        ESP_LOGI(TAG, "Committing updates in NVS ... ");
        err = nvs_commit(my_handle);
        printf((err != ESP_OK) ? "Failed!\n" : "Done\n");

        nvs_close(my_handle);
    }
}
